package com.sservice.web.controller.admin;

import com.alibaba.fastjson.JSONObject;
import com.sservice.base.entity.dto.BaseResult;
import com.sservice.base.entity.dto.ListResult;
import com.sservice.base.entity.dto.Pagination;
import com.sservice.common.CompareObject;
import com.sservice.common.SameUrlData;
import com.sservice.commonBusiness.e.Category;
import com.sservice.commonBusiness.service.CategoryService;
import com.sservice.service.service.*;
import com.sservice.urp.dao.IUserDao;
import com.sservice.urp.dao.IUserRoleDao;
import com.sservice.urp.entity.Com;
import com.sservice.urp.entity.User;
import com.sservice.urp.entity.UserRole;
import com.sservice.urp.vo.ComVo;
import com.sservice.urp.vo.DepVo;
import com.sservice.urp.vo.UserVo;
import com.sservice.web.log.Action;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/admin/com")
public class ComController {
//    private Logger logger = LoggerFactory.getLogger(this.getClass());

    //    @Resource
//    WebsocketEndPoint websocket;
    @Autowired
    private IComService comService;
    @Autowired
    private ISysLogService sysLogService;
    @Autowired
    private IDepService depService;
    @Autowired
    private IUserService userService;


    @Autowired
    ExportService exportService;
    @Autowired
    CategoryService categoryService;

    /**
     * 司法机构导入数据数据导入
     */
    @ResponseBody
    @RequestMapping(value = "/import/org", method = RequestMethod.POST)
    public BaseResult importData(@RequestParam("file") MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws IOException {
        if (file.isEmpty()) {
            return new BaseResult(false, "file is empty", 400);
        }
        response.setHeader("Content-type", "text/html");
        //图片保存路径
        List list = exportService.importExcel(file.getInputStream());
        for (int i = 0; i < list.size(); i++) {
            JSONObject jo = (JSONObject) list.get(i);
            //judicial-organ
            Category category = new Category();
            category.setType1("judicial-organ");
            category.setName(jo.getString("name"));
            category.setDesc1(jo.getString("address"));
            category.setRemark(jo.getString("phone"));
            category.setEn(jo.getString("x") + "," + jo.getString("y"));
            Com com = comService.judgeRegion(jo.getString("region"));
            if (com != null) //存在
                category.setComId(com.getId().toString());
            categoryService.insertSelective(category);
        }
        BaseResult res = new BaseResult(true, 1);
        return res;
    }

    /**
     *     基层工作者信息导入
     */

    /**
     * 倒入律师擅长领域
     *
     * @param file
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @Autowired
    IUserDao iUserDao;

    @ResponseBody
    @RequestMapping(value = "/import/lawMember", method = RequestMethod.POST)
    public BaseResult lawMember(@RequestParam("file") MultipartFile file, HttpServletResponse response) throws IOException {
        if (file.isEmpty()) {
            return new BaseResult(false, "file is empty", 400);
        }
        response.setHeader("Content-type", "text/html");
        //图片保存路径
        List list = exportService.imporLawDomain(file.getInputStream());
        for (int i = 0; i < list.size(); i++) {
            JSONObject jo = (JSONObject) list.get(i);
            User user = new User();
            user.setType("laws_official");// 律师
            user.setName(jo.getString("name").replace(" ", ""));
            User user1 = iUserDao.selectOneBy(user);
            if (user1 != null) {
                user1.setProfessionalDomain(jo.getString("domain"));
                iUserDao.updateByPrimaryKeySelective(user1);
            }
        }
        BaseResult res = new BaseResult(true, 1);
        return res;
    }

    /**
     * 预警关键词导入
     *
     * @param file
     * @param response
     * @return
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping(value = "/import/earlyWarning", method = RequestMethod.POST)
    public BaseResult earlyWarning(@RequestParam("file") MultipartFile file, HttpServletResponse response) throws IOException {
        if (file.isEmpty()) {
            return new BaseResult(false, "file is empty", 400);
        }
        response.setHeader("Content-type", "text/html");
        //图片保存路径
        List list = exportService.imporEarlyWarning(file.getInputStream());
        for (int i = 0; i < list.size(); i++) {
            JSONObject jo = (JSONObject) list.get(i);
            Category category = new Category();
            category.setType1("earlyWarning");// 律师
            category.setName(jo.getString("name").replace(" ", ""));
            Category category1 = categoryService.selectBy(category);
            if (category1 == null) {
                categoryService.insertSelective(category);
            }
        }
        BaseResult res = new BaseResult(true, 1);
        return res;
    }

    @ResponseBody
    @RequestMapping(value = "/import/jicengorg", method = RequestMethod.POST)
    public BaseResult importjiceData(@RequestParam("file") MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws IOException {
        if (file.isEmpty()) {
            return new BaseResult(false, "file is empty", 400);
        }
        response.setHeader("Content-type", "text/html");
        //图片保存路径
        List list = exportService.importjicengExcel(file.getInputStream());
        for (int i = 0; i < list.size(); i++) {
            JSONObject jo = (JSONObject) list.get(i);
            User user = new User();
            user.setType("laws_official");// 律师
            user.setName(jo.getString("name"));
            user.setQq(jo.getString("qq"));
            if (jo.getString("genter").equals("男")) {
                user.setGender(1);
            }
            if (jo.getString("genter").equals("女")) {
                user.setGender(0);
            }
            user.setUserName(jo.getString("userName"));
            user.setDepName(jo.getString("depName"));
            user.setPhone(jo.getString("phone"));
            user.setComName(jo.getString("comName"));
            user.setRemark(jo.getString("remark"));
            user.setProfessionalDomain(jo.getString("professionalDomain"));
            user.setPassword("e10adc3949ba59abbe56e057f20f883e");// 默认密码123456
            Com com = comService.judgeRegion(jo.getString("region"));
            if (com != null) //存在
                user.setComid(com.getId());
            userService.insertSelective(user);
        }
        BaseResult res = new BaseResult(true, 1);
        return res;
    }


    @ResponseBody
    @RequestMapping(value = "/import/lawLeader", method = RequestMethod.POST)
    public BaseResult lawLeader(@RequestParam("file") MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws IOException {
        if (file.isEmpty()) {
            return new BaseResult(false, "file is empty", 400);
        }
        response.setHeader("Content-type", "text/html");
        //图片保存路径
        List list = exportService.importLawLeaderExcel(file.getInputStream());
        for (int i = 0; i < list.size(); i++) {
            JSONObject jo = (JSONObject) list.get(i);
            User user = new User();
            user.setType("law-leader");// 所长
            user.setName(jo.getString("name"));
            user.setUserName(jo.getString("phone"));
            user.setComid(Integer.valueOf(jo.getString("comId")));
            user.setPhone(jo.getString("phone"));
            user.setComName(jo.getString("region")); //区县
            user.setRemark(jo.getString("org"));//司法所
            Category category = new Category();
            category.setName(jo.getString("location"));
            category.setComId("" + user.getComid());//
            category.setType1("street");
            categoryService.insertSelective(category);
            user.setDepid(category.getId());//街道ID
            user.setPassword("e10adc3949ba59abbe56e057f20f883e");// 默认密码123456
            userService.insertSelective(user);
            List list1 = new ArrayList();
            UserRole userRole = new UserRole();
            userRole.setUserId(Integer.valueOf(user.getId()));//
            userRole.setRoleId(Integer.valueOf(42));//法律咨询解答人
            list1.add(userRole);
            iUserRoleDao.addBatch(list1);
        }
        BaseResult res = new BaseResult(true, 1);
        return res;
    }


    /**
     * 用户管理工作者信息导入
     */
    @ResponseBody
    @RequestMapping(value = "/import/usercengorg", method = RequestMethod.POST)
    public BaseResult importuserData(@RequestParam("file") MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws IOException {
        if (file.isEmpty()) {
            return new BaseResult(false, "file is empty", 400);
        }
        response.setHeader("Content-type", "text/html");
        //图片保存路径
        List list = exportService.importusercengExcel(file.getInputStream());
        for (int i = 0; i < list.size(); i++) {
            JSONObject jo = (JSONObject) list.get(i);
            //judicial-organ
            User user = new User();
            user.setName(jo.getString("name"));
            user.setPhone(jo.getString("phone"));
            Com com = comService.judgeRegion(jo.getString("depName"));
            user.setPassword("e10adc3949ba59abbe56e057f20f883e");// 默认密码123456
            user.setDepid(43);
            if (com != null) //存在
                user.setComid(com.getId());


            userService.insertSelective(user);

            List list1 = new ArrayList();
            UserRole userRole = new UserRole();
            userRole.setUserId(Integer.valueOf(user.getId()));
            userRole.setRoleId(Integer.valueOf(43));
            list1.add(userRole);
            iUserRoleDao.addBatch(list1);
            // return new BaseResult(true, );
        }
        BaseResult res = new BaseResult(true, 1);
        return res;
    }

    @Autowired
    IUserRoleDao iUserRoleDao;

    /**
     * 南平市各区县援助中心联系人导入
     */
    @ResponseBody
    @RequestMapping(value = "/import/helpcenter", method = RequestMethod.POST)
    public BaseResult importhelpcenter(@RequestParam("file") MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws IOException {
        if (file.isEmpty()) {
            return new BaseResult(false, "file is empty", 400);
        }
        response.setHeader("Content-type", "text/html");
        //图片保存路径
        List list = exportService.importhelpExcel(file.getInputStream());
        for (int i = 0; i < list.size(); i++) {
            JSONObject jo = (JSONObject) list.get(i);
            //judicial-organ
            User user = new User();
            user.setName(jo.getString("name"));
            user.setPhone(jo.getString("phone"));
            user.setQq(jo.getString("qq"));
            user.setJobNum(jo.getString("jobNum"));
            user.setDepName(jo.getString("depName"));
            user.setType("helpCenter");
            Com com = comService.judgeRegion(jo.getString("jobNum"));
            user.setPassword("e10adc3949ba59abbe56e057f20f883e");// 默认密码123456
            user.setDepid(46);
            if (com != null) //存在
                user.setComid(com.getId());

            userService.insertSelective(user);

            List list1 = new ArrayList();
            UserRole userRole = new UserRole();
            userRole.setUserId(Integer.valueOf(user.getId()));
            userRole.setRoleId(Integer.valueOf(43));
            list1.add(userRole);
            iUserRoleDao.addBatch(list1);
            // return new BaseResult(true, );
        }
        BaseResult res = new BaseResult(true, 1);
        return res;
    }


    /**
     * 街乡工作站信息人员
     */
    @ResponseBody
    @RequestMapping(value = "/import/cityStatie", method = RequestMethod.POST)
    public BaseResult importcityStatie(@RequestParam("file") MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws IOException {

        if (file.isEmpty()) {
            return new BaseResult(false, "file is empty", 400);
        }
        response.setHeader("Content-type", "text/html");
        //图片保存路径
        List list = exportService.importstatieExcel(file.getInputStream());
        for (int i = 0; i < list.size(); i++) {
            JSONObject jo = (JSONObject) list.get(i);
            //judicial-organ
            Category c = new Category();
            c.setName(jo.getString("name"));
            c.setDesc1(jo.getString("comName"));
            c.setEn(jo.getString("phone"));
            c.setUrl(jo.getString("depName"));
            c.setType1("city-statie");
            Com com = comService.judgeRegion(jo.getString("jobNum"));
            if (com != null) //存在
                c.setComId(com.getId().toString());
            categoryService.insertSelective(c);
        }
        BaseResult res = new BaseResult(true, 1);
        return res;
    }


    /**
     * 创建
     *
     * @return
     */
    @SameUrlData
    @ResponseBody
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public BaseResult<Object> create(Com arg, HttpServletRequest request) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        Com com = comService.selectByComName(arg.getName().trim());
        if (com != null) {
            return new BaseResult(false, "单位名称已存在!", 403);
        }
        int service_res = comService.insertSelective(arg);
        if (service_res > 0) {
            sysLogService.log("创建", request, Integer.valueOf(arg.getId()), Action.comType);
        }
        BaseResult res = new BaseResult(true, service_res);
        return res;
    }

    /***
     *  单位详情
     * @param arg
     * @param request
     * @return
     * @throws NoSuchMethodException
     * @throws IllegalAccessException
     * @throws InvocationTargetException
     */
    @ResponseBody
    @RequestMapping(value = "/get", method = RequestMethod.GET)
    public BaseResult<Object> get(Com arg, HttpServletRequest request) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        Com com = comService.selectByPrimaryKey(arg.getId());
        return new BaseResult(true, com);
    }

    /**
     * @param arg
     * @return
     */
    @SameUrlData
    @ResponseBody
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public BaseResult<Object> delete(Com arg, HttpServletRequest request) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        DepVo dv = new DepVo();
        UserVo uv = new UserVo();
        BaseResult<Object> res;
        dv.setComid(String.valueOf(arg.getId()));
        uv.setComid(arg.getId());
        if (depService.queryCountByComId(dv) > 0) {
            res = new BaseResult<Object>(false, "该公司关联部门，不能删除!", 403);
        } else if (userService.queryCountByComId(uv) > 0) {
            res = new BaseResult<Object>(false, "该公司关联用户，不能删除!", 403);
        } else {
            int service_res = comService.deleteByPrimaryKey(arg.getId());
            if (service_res > 0) {
                sysLogService.log("删除", request, Integer.valueOf(arg.getId()), Action.comType);
            }
            res = new BaseResult<Object>(true, service_res);
        }
        return res;
    }

    /**
     * @param arg
     * @return
     */
    @SameUrlData
    @ResponseBody
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public BaseResult<Integer> update(Com arg, HttpServletRequest request) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        Com com = comService.selectByPrimaryKey(arg.getId());
        int service_res = comService.updateByPrimaryKeySelective(arg);
        if (service_res > 0) {

            Map<String, Object> res = CompareObject.contrastObj(arg, com);
            if (res.get("signature") != null) {
                sysLogService.log("更改公章：" + res.get("signature"), request, Integer.valueOf(arg.getId()), Action.comType);
            }
            if (res.get("signaturePaper") != null) {
                sysLogService.log("更改合同章：" + res.get("signaturePaper"), request, Integer.valueOf(arg.getId()), Action.comType);
            }
            if (res.get("signatureFinance") != null) {
                sysLogService.log("更改财务章：" + res.get("signatureFinance"), request, Integer.valueOf(arg.getId()), Action.comType);
            }
            sysLogService.log(res, request, Integer.valueOf(arg.getId()), Action.comType);
        }
        BaseResult<Integer> res = new BaseResult<Integer>(true, service_res);
        return res;
    }


    /***
     * 分页查询
     * @param arg
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/query", method = RequestMethod.GET)
    public ListResult query(ComVo arg) {
        List<Com> list = comService.queryByPage(arg);
        int total = comService.queryCount(arg);
        Pagination page = new Pagination(arg.getPage(), total, arg.getSize());
        ListResult res = new ListResult(true, list);
        res.setPage(page);
        return res;
    }
}
